package com.ruoyi.web.controller.credit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.CreditUserInfo;
import com.ruoyi.system.domain.CreditTask;
import com.ruoyi.system.service.ICreditUserInfoService;
import com.ruoyi.system.service.ICreditTaskService;

/**
 * 信用分展示Controller
 * 
 * @author ruoyi
 * @date 2025-01-28
 */
@RestController
@RequestMapping("/credit/score")
public class CreditScoreController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(CreditScoreController.class);
    
    @Autowired
    private ICreditUserInfoService creditUserInfoService;

    @Autowired
    private ICreditTaskService creditTaskService;

    /**
     * 获取当前用户信用分信息
     */
    @PreAuthorize("@ss.hasPermi('credit:score:view')")
    @GetMapping("/getScore")
    public AjaxResult getScore()
    {
        Long userId = getUserId();
        CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
        
        if (userInfo == null)
        {
            // 如果用户信用信息不存在，初始化默认信用信息
            userInfo = new CreditUserInfo();
            userInfo.setUserId(userId);
            userInfo.setCreditScore(600);
            userInfo.setLifeServiceScore(200);
            userInfo.setBusinessScore(200);
            userInfo.setSocialScore(200);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("userInfo", userInfo);
        result.put("totalScore", userInfo.getCreditScore());
        result.put("lastUpdateTime", userInfo.getLastUpdateTime());
        
        return success(result);
    }

    /**
     * 获取当前用户信用分信息（信用员专用，无权限）
     */
    @GetMapping("/getScoreNoAuth")
    public AjaxResult getScoreNoAuth()
    {
        Long userId = getUserId();
        CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
        
        if (userInfo == null)
        {
            // 如果用户信用信息不存在，自动初始化默认信用信息
            try {
                creditUserInfoService.initUserCreditInfo(userId, null);
                userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            } catch (Exception e) {
                logger.error("自动初始化用户信用信息失败", e);
            }
            
            // 如果初始化失败，创建临时对象
            if (userInfo == null) {
                userInfo = new CreditUserInfo();
                userInfo.setUserId(userId);
                userInfo.setCreditScore(600);
                userInfo.setLifeServiceScore(200);
                userInfo.setBusinessScore(200);
                userInfo.setSocialScore(200);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("userInfo", userInfo);
        result.put("totalScore", userInfo.getCreditScore());
        result.put("lastUpdateTime", userInfo.getLastUpdateTime());
        
        return success(result);
    }

    /**
     * 获取维度分析数据
     */
    @PreAuthorize("@ss.hasPermi('credit:score:view')")
    @GetMapping("/analyDimen")
    public AjaxResult analyDimen()
    {
        Long userId = getUserId();
        CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
        
        if (userInfo == null)
        {
            // 如果用户信用信息不存在，自动初始化默认信用信息
            try {
                creditUserInfoService.initUserCreditInfo(userId, null);
                userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            } catch (Exception e) {
                logger.error("自动初始化用户信用信息失败", e);
            }
            
            // 如果初始化失败，创建临时对象
            if (userInfo == null) {
                userInfo = new CreditUserInfo();
                userInfo.setUserId(userId);
                userInfo.setCreditScore(600);
                userInfo.setLifeServiceScore(200);
                userInfo.setBusinessScore(200);
                userInfo.setSocialScore(200);
            }
        }

        Map<String, Object> result = new HashMap<>();
        
        // 各维度分数
        Map<String, Integer> dimensions = new HashMap<>();
        dimensions.put("lifeService", userInfo.getLifeServiceScore());
        dimensions.put("business", userInfo.getBusinessScore());
        dimensions.put("social", userInfo.getSocialScore());
        
        // 计算各维度占比
        int totalScore = userInfo.getCreditScore();
        Map<String, Double> percentage = new HashMap<>();
        if (totalScore > 0) {
            percentage.put("lifeService", (double) userInfo.getLifeServiceScore() / totalScore * 100);
            percentage.put("business", (double) userInfo.getBusinessScore() / totalScore * 100);
            percentage.put("social", (double) userInfo.getSocialScore() / totalScore * 100);
        }
        
        result.put("dimensions", dimensions);
        result.put("percentage", percentage);
        
        return success(result);
    }

    /**
     * 获取维度分析数据（信用员专用，无权限）
     */
    @GetMapping("/analyDimenNoAuth")
    public AjaxResult analyDimenNoAuth()
    {
        Long userId = getUserId();
        CreditUserInfo userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
        
        if (userInfo == null)
        {
            // 如果用户信用信息不存在，自动初始化默认信用信息
            try {
                creditUserInfoService.initUserCreditInfo(userId, null);
                userInfo = creditUserInfoService.selectCreditUserInfoByUserId(userId);
            } catch (Exception e) {
                logger.error("自动初始化用户信用信息失败", e);
            }
            
            // 如果初始化失败，创建临时对象
            if (userInfo == null) {
                userInfo = new CreditUserInfo();
                userInfo.setUserId(userId);
                userInfo.setCreditScore(600);
                userInfo.setLifeServiceScore(200);
                userInfo.setBusinessScore(200);
                userInfo.setSocialScore(200);
            }
        }

        Map<String, Object> result = new HashMap<>();
        
        // 各维度分数
        Map<String, Integer> dimensions = new HashMap<>();
        dimensions.put("lifeService", userInfo.getLifeServiceScore());
        dimensions.put("business", userInfo.getBusinessScore());
        dimensions.put("social", userInfo.getSocialScore());
        
        // 计算各维度占比
        int totalScore = userInfo.getCreditScore();
        Map<String, Double> percentage = new HashMap<>();
        if (totalScore > 0) {
            percentage.put("lifeService", (double) userInfo.getLifeServiceScore() / totalScore * 100);
            percentage.put("business", (double) userInfo.getBusinessScore() / totalScore * 100);
            percentage.put("social", (double) userInfo.getSocialScore() / totalScore * 100);
        }
        
        result.put("dimensions", dimensions);
        result.put("percentage", percentage);
        
        return success(result);
    }

    /**
     * 获取提升任务列表
     */
    @PreAuthorize("@ss.hasPermi('credit:score:view')")
    @GetMapping("/getTask")
    public AjaxResult getTask()
    {
        // 查询可用的提升任务
        CreditTask queryTask = new CreditTask();
        queryTask.setStatus("0"); // 正常状态
        List<CreditTask> taskList = creditTaskService.selectCreditTaskList(queryTask);
        
        Map<String, Object> result = new HashMap<>();
        result.put("taskList", taskList);
        
        return success(result);
    }

    /**
     * 获取提升任务列表（信用员专用，无权限）
     */
    @GetMapping("/getTaskNoAuth")
    public AjaxResult getTaskNoAuth()
    {
        // 查询可用的提升任务
        CreditTask queryTask = new CreditTask();
        queryTask.setStatus("0"); // 正常状态
        List<CreditTask> taskList = creditTaskService.selectCreditTaskList(queryTask);
        
        Map<String, Object> result = new HashMap<>();
        result.put("taskList", taskList);
        
        return success(result);
    }

    /**
     * 根据任务类型获取提升任务
     */
    @PreAuthorize("@ss.hasPermi('credit:score:view')")
    @GetMapping("/getTask/{taskType}")
    public AjaxResult getTaskByType(@PathVariable String taskType)
    {
        List<CreditTask> taskList = creditTaskService.selectAvailableCreditTaskList(taskType);
        
        Map<String, Object> result = new HashMap<>();
        result.put("taskList", taskList);
        
        return success(result);
    }

    /**
     * 根据任务类型获取提升任务（信用员专用，无权限）
     */
    @GetMapping("/getTaskNoAuth/{taskType}")
    public AjaxResult getTaskByTypeNoAuth(@PathVariable String taskType)
    {
        List<CreditTask> taskList = creditTaskService.selectAvailableCreditTaskList(taskType);
        
        Map<String, Object> result = new HashMap<>();
        result.put("taskList", taskList);
        
        return success(result);
    }

    /**
     * 完成任务并获得积分
     */
    @PreAuthorize("@ss.hasPermi('credit:score:view')")
    @Log(title = "完成任务", businessType = BusinessType.UPDATE)
    @GetMapping("/completeTask/{taskId}")
    public AjaxResult completeTask(@PathVariable Long taskId)
    {
        Long userId = getUserId();
        
        // 查询任务信息
        CreditTask task = creditTaskService.selectCreditTaskByTaskId(taskId);
        if (task == null)
        {
            return error("任务不存在");
        }
        
        if (!"0".equals(task.getStatus()))
        {
            return error("任务已停用");
        }

        // 更新用户信用分
        boolean result = creditUserInfoService.updateUserCreditScore(
            userId, 
            task.getScoreReward(), 
            task.getTaskType(), 
            "完成任务：" + task.getTaskName(),
            taskId
        );
        
        if (result)
        {
            return success("任务完成，获得 " + task.getScoreReward() + " 积分");
        }
        else
        {
            return error("任务完成失败");
        }
    }

    /**
     * 完成任务并获得积分（信用员专用，无权限）
     */
    @Log(title = "完成任务", businessType = BusinessType.UPDATE)
    @PostMapping("/completeTaskNoAuth")
    public AjaxResult completeTaskNoAuth(@RequestBody Map<String, Object> params)
    {
        Long userId = getUserId();
        Long taskId = Long.valueOf(params.get("taskId").toString());
        
        // 查询任务信息
        CreditTask task = creditTaskService.selectCreditTaskByTaskId(taskId);
        if (task == null)
        {
            return error("任务不存在");
        }
        
        if (!"0".equals(task.getStatus()))
        {
            return error("任务已停用");
        }

        // 更新用户信用分
        boolean result = creditUserInfoService.updateUserCreditScore(
            userId, 
            task.getScoreReward(), 
            task.getTaskType(), 
            "完成任务：" + task.getTaskName(),
            taskId
        );
        
        if (result)
        {
            return success("任务完成，获得 " + task.getScoreReward() + " 积分");
        }
        else
        {
            return error("任务完成失败");
        }
    }

    /**
     * 获取信用分历史记录
     */
    @PreAuthorize("@ss.hasPermi('credit:score:view')")
    @GetMapping("/history")
    public AjaxResult getCreditHistory()
    {
        Long userId = getUserId();
        Map<String, Object> history = creditUserInfoService.getCreditScoreHistory(userId, 1, 10);
        return success(history);
    }

    /**
     * 获取信用分历史记录（信用员专用，无权限）
     */
    @GetMapping("/historyNoAuth")
    public AjaxResult getCreditHistoryNoAuth()
    {
        Long userId = getUserId();
        Map<String, Object> history = creditUserInfoService.getCreditScoreHistory(userId, 1, 10);
        return success(history);
    }
} 